package cn.webrx;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class T2 {
    public static void main(String[] args) {
        String f = "user.db";
        write(new File(f));
        System.out.println(read(new File(f)));
    }

    public static void write(File file) {
        List<Student> list = new ArrayList<Student>();
        if (list.isEmpty()) {
            list = read(file);
        }
        try (var o = new ObjectOutputStream(new FileOutputStream(file))) {
            list.add(new Student("李丽", 18, "女"));
            o.writeObject(list);
            System.out.println("存储完成");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static List<Student> read(File file) {
        init(file);
        List<Student> list = new ArrayList<Student>();
        try (var r = new ObjectInputStream(new FileInputStream(file))) {
            list = (List<Student>) r.readObject();
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
            System.out.println("读取完成");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static void init(File file) {
        if (!file.exists()) {
            try (var o = new ObjectOutputStream(new FileOutputStream(file))) {
                List<Student> init = new ArrayList<Student>();
                o.writeObject(init);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class Student implements Serializable {
    String name;
    int age;
    String sex;

    public Student(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
}
